package com.etoak.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.vo.ResultVO;

import com.etoak.common.web.properties.ImageProperties;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/img")
    public ResultVO<String> upload(MultipartFile image) {
        // 判断是否为空
        if(ObjectUtils.isEmpty(image) || image.isEmpty()) {
            return ResultVO.failed(500, "图片不能为空");
        }

        // 判断图片格式是否正确
        List<String> types = imageProperties.getTypes();
        if(!types.contains(image.getContentType())){
            String msg = types.stream()
                    .map(v -> v.substring(v.lastIndexOf("/") + 1))
                    .collect(Collectors.joining("、"));
            return ResultVO.failed(500,"图片格式错误，仅允许" + msg);
        }

        // 创建图片存储路径
        String location = imageProperties.getLocation();
        File parent = new File(location);
        if (!parent.exists()) {
            parent.mkdirs();
        }

        // 随机生成uuid作为图片名
        String originalFilename = image.getOriginalFilename();
        String endFix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = IdUtil.simpleUUID() + endFix;
        File targetFile = new File(parent, fileName);

        // 上传图片
        try {
            image.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回 /files/图片名
        String result = imageProperties.getPrefix().endsWith("/")
                ? StringUtils.join(imageProperties.getPrefix(), fileName)
                : StringUtils.join(imageProperties.getPrefix(), "/", fileName);

        return ResultVO.success(result);
    }

}
